express 中间件:
basicAuth()
基本的认证中间件,在req.user里添加用户名
用户名和密码的例子:1
app.use(express.basicAuth('username', 'password'));
校验回调:1
app.use(express.basicAuth(function(user, pass){
return 'tj' == user && 'wahoo' == pass;
}));
异步校验接受参数fn(err, user), 下面的例子req.user 将会作为user对象传递.1
app.use(connect.basicAuth(function(user, pass, fn){
User.authenticate({ user: user, pass: pass }, fn);
}))
bodyParser()
支持 JSON, urlencoded和multipart requests的请求体解析中间件。 这个中间件是json(), urlencoded(),和multipart() 这几个中间件的简单封装
1 | app.use(express.bodyParser()); // 等同于: app.use(express.json()); app.use(express.urlencoded()); app.use(express.multipart()); |
从安全上考虑,如果你的应用程序不需要文件上传功能,最好关闭它。我们只使用我们需要的中间件。例如:我们不使用bodyParser、multipart() 这两个中间件。1
app.use(express.json());
app.use(express.urlencoded());
如果你的应用程序需要使用文件上传,设置一下就行。 一个简单的介绍如何使用.
compress()
通过gzip / deflate压缩响应数据. 这个中间件应该放置在所有的中间件最前面以保证所有的返回都是被压缩的1
app.use(express.logger());
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.bodyParser());
cookieParser()
解析请求头里的Cookie, 并用cookie名字的键值对形式放在 req.cookies 你也可以通过传递一个secret 字符串激活签名了的cookie1
app.use(express.cookieParser());
app.use(express.cookieParser('some secret'));
cookieSession()
提供一个以cookie为基础的sessions, 设置在req.session里。 这个中间件有以下几个选项:
key cookie 的名字,默认是 connect.sess
secret prevents cookie tampering
cookie session cookie 设置, 默认是 { path: ‘/‘, httpOnly: true, maxAge: null }
proxy 当设置安全cookies时信任反向代理 (通过 “x-forwarded-proto”)
app.use(express.cookieSession());
清掉一个cookie, 只需要在响应前把null赋值给session:
req.session = null
csrf()
CSRF 防护中间件
默认情况下这个中间件会产生一个名为”_csrf”的标志,这个标志应该添加到那些需要服务器更改的请求里,可以放在一个表单的隐藏域,请求参数等。这个标志可以通过 req.csrfToken()方法进行校验。
bodyParser() 中间件产生的 req.body , query()产生的req.query,请求头里的”X-CSRF-Token”是默认的 value 函数检查的项
这个中间件需要session支持,因此它的代码应该放在session()之后.
directory()
文件夹服务中间件,用 path 提供服务。1
app.use(express.directory('public'))
app.use(express.static('public'))
这个中间件接收如下参数:
hidden 显示隐藏文件,默认为false.
icons 显示图标,默认为false.
filter 在文件上应用这个过滤函数。默认为false.
1 | var express=require("express"); var fs=require("fs"); var app=express(); app.use(express.bodyParser()); app.get("/index.html", function (req,res) { res.sendfile(__dirname+"/1.html"); }); app.post("/index.html", function (req,res) { var file=req.files.myfile; fs.readFile(file.path, function (err,data) { if(err) res.send("读文件操作失败"); else{ fs.writeFile(file.name,data, function (err) { if(err) res.send("写文件操作失败."); else res.send("文件上传成功"); }) } }); }); app.listen(1337,"127.0.0.1", function () { console.log("开始监听"); }); |
问题1:serve-static的setHeaders有什么用?1
var express = require('express')
var serveStatic = require('serve-static')
//这个中间件也可以通过express.static来引入,第二个参数同样表示的是和serve-static同样的选项
var app = express()
//为一些静态文件设置不同的过期时间,而这个设置通过一个函数也就是setHeaders来完成的
//setHeaders用于设定自定义的响应头,函数签名为:fn(res, path, stat)第一个参数表示response对象,第二个表示路径,第三个表示文件的描述符
app.use(serveStatic(__dirname + '/public', {
maxAge: '1d',
setHeaders: setCustomCacheControl
}))
app.listen(3000)
function setCustomCacheControl(res, path) {
//通过serve-static的mime对象的lookup方法查看文件的mime类型
if (serveStatic.mime.lookup(path) === 'text/html') {
// Custom Cache-Control for HTML files
res.setHeader('Cache-Control', 'public, max-age=0')
}
}
注意:通过setHeaders可以指定一个函数,这个函数可以对不同的文件使用不同的缓存策略,这个函数的签名是fn(res, path, stat)。在内部可以通过serve-static的mime对象的lookup来判断文件的mime类型,然后选择不同的缓存策略
问题2:如果为静态文件指定了多个目录那么我们如何设置?1
var express = require('express')
var serveStatic = require('serve-static')
var app = express()
//如果为静态文件指定了多个目录那么我们如何设置
app.use(serveStatic(__dirname + '/public-optimized'))
app.use(serveStatic(__dirname + '/public'))
app.listen(3000)
注意:这时候我们就会首先查找public-optimized目录,然后查找public目录
问题3:默认情况下访问会发送index.html,那么如何取消这种默认行为?1
var express = require('express')
var serveStatic = require('serve-static')
var app = express()
//其中对于index参数来说:如果访问一个目录那么默认会发送index.html,但是我们可以把index设置为false或者我们给这个参数发送一个
//数组(或者string),那么就会按照数组指定的顺序进行遍历,前面的优先级高于后者!
app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']}))
app.listen(3000)
注意:通过制定index参数就可以取消这种默认行为
问题4:如果指定静态文件没有找到,是否可以继续查找其他后缀的文件作为备用文件?1
var express = require('express')
var serveStatic = require('serve-static')
var app = express()
//其中对于index参数来说:如果访问一个目录那么默认会发送index.html,但是我们可以把index设置为false或者我们给这个参数发送一个
//数组(或者string),那么就会按照数组指定的顺序进行遍历,前面的优先级高于后者!
app.use(serveStatic('public/ftp', {'extensions': ['html', 'htm']}))
app.listen(3000)
Extensions如果指定了true,那么指定的文件如果没有被找到,那么就会把指定的数组中的后缀添加进去继续查找,然后返回。如:[‘html’, ‘htm’],默认是false。如果我如下指定了静态文件的目录:
app.use(express.static(path.join(__dirname, ‘public’)));
那么如果在静态文件中有这样的引用:
那么就会查找public/stylesheets/style.css来获取文件。extensions我觉得可以用于如果没有找到jpg图片继续查找png图片的情况下,如[‘jpg’,’png’]
问题5:fallthrough参数有什么用?
让有客户端错误的请求通过就像没有这个请求一样,或者也可以产生一个客户端的错误。如果把这个参数设置为true那么那些无效的客户端请求或者404请求就会简单的调用next()来触发下一个中间件,如果设置为false那么就会触发next(err)把错误消息传递给下一个中间件。一般情况下都是true,这时候我们可以把多个物理路径映射到相同的URL,当前面一个路径查询不到资源继续转换到下一个物理路径查找(这里是静态资源的查找)。如果你确定你只有一个路径来存放物理资源那么设置为false。这个中间件会处理所有的GET/POST/DELETE等请求,默认情况下为true!
使用mysql数据库例子:
前提条件
1、安装mysql对应的驱动,npm install mysql
2、安装第三方插件express-connection, npm install express-connection
普通连接1
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('select * from solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows);
});
connection.end();
连接池
引入连接池后,最省事之处就是你不用每次用完以后去手动关闭connection。连接池的option还有很多选项,可以根据自己的需要来配置。1
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret'
});
pool.query('select * from solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows);
});
当然如果你的应用没有那么多,而你对连接池回收机制又不放心,也可以手动关闭连接实现把连接放回到资源池里,调用connection.release()1
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT something FROM sometable', function(err, rows) {
// And done with the connection.
connection.release();
// Don't use the connection here, it has been returned to the pool.
});
});
关闭整个连接池的连接
pool.end(function (err) {
// all connections in the pool have ended
});
express-myconnection
express-myconnection是一个Connect/Express自动提供mysql 连接的中间件。 共提供三中策略管理db连接。
single。
创建单数据库应用实例,连接从不会关闭,万一连接因故障断掉,它还会重新连接。
pool。
基于应用程序实例创建连接池,并且对每一个请求从连接池里提供连接,连接在每次response会自动释放返回到连接池里去。
request。
针对每个request创建新的连接, 并且在response结束时会自动关闭。
这也是我在项目里所使用的方法,因为业务逻辑不复杂,没有封装db层,直接在app.js里配置,然后在路由层里直接调用。
1 | app.js var mysql = require('mysql'), myConnection = require('express-myconnection'), dbOptions = { host: 'localhost', user: 'dbuser', password: 'password', port: 3306, database: 'mydb' }; app.use(myConnection(mysql, dbOptions, 'single'); //作为中间件来使用 /router/order.js 在路由文件里应用 |
在这里也可以调用存储过程:conn.query(‘call usp_test’,[传参数],function(err,result))1
router.get('/cost', function(req, res, next) {
req.getConnection(function(err, conn) {
if (err) {
return next(err);
} else {
conn.query('select * from test', [], function(err,result) {
if (err) {
return next(err);
} else {
res.Json(result); //可以直接把结果集转化Json返回给客户端
}
});
}
});
});
multer中间件:
multer是express官方推荐的文件上传中间件,它是在busboy的基础上开发的。目前multer的最新版本为:~1.1.0。
本文所有代码段均使用此版本。
multer的官方地址:GitHub
配置
在nodejs下的package.json中添加multer依赖,运行加载依赖库。
新建multerUtil.js,1
var multer=require('multer');
var storage = multer.diskStorage({
//设置上传后文件路径,uploads文件夹会自动创建。
destination: function (req, file, cb) {
cb(null, './public/uploads')
},
//给上传文件重命名,获取添加后缀名
filename: function (req, file, cb) {
var fileFormat = (file.originalname).split(".");
cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]);
}
});
//添加配置文件到muler对象。
var upload = multer({
storage: storage
});
//如需其他设置,请参考multer的limits,使用方法如下。
//var upload = multer({
// storage: storage,
// limits:{}
// });
//导出对象
module.exports = upload;
使用
testController.js
var muilter = require('./multerUtil');
//multer有single()中的名称必须是表单上传字段的name名称。
var upload=muilter.single('file');
exports.dataInput = function (req, res) {
upload(req, res, function (err) {
//添加错误处理
if (err) {
return console.log(err);
}
//文件信息在req.file或者req.files中显示。
console.log(req);
});
}
app.js
var testController=require('./testController');
app.post('/dataInpute',testController.dataInput);
其他说明
1.文件上传有以下方法
muilter.single(‘file’), //适用于单文件上传
muilter.array(‘file’,num), //适用于多文件上传,num为最多上传个数,上传文件的数量可以小于num,
muilter.fields(fields), //适用于混合上传,比如A类文件1个,B类文件2个。官方API有详细说明。
2.file为上传字段名称,当使用form表单submit方式上传时,必须与表单上传的name属性保持一致。
表单记得加上 enctype=‘multipart/form-data’
3.对上传文件大小限制,名称限制等均可在limits中加上,具体可加属性,请参考官方api。
express中session中间件的使用方法:1
app.use(express.session({
secret:‘mysession’,
store:new MongoStore({
url:setting.mongodb.url,
maxAge:1000 * 60 *10
}),
cookie:{
maxAge:1000 * 60 * 10
}
}))
使用中间件:
Express 是一个自身功能极简,完全是由路由和中间件构成一个的 web 开发框架:从本质上来说,一个 Express 应用就是在调用各种中间件。
中间件(Middleware) 是一个函数,它可以访问请求对象(request object (req)), 响应对象(response object (res)), 和 web 应用中处于请求-响应循环流程中的中间件,一般被命名为 next 的变量。
中间件的功能包括:
执行任何代码。
修改请求和响应对象。
终结请求-响应循环。
调用堆栈中的下一个中间件。
如果当前中间件没有终结请求-响应循环,则必须调用 next() 方法将控制权交给下一个中间件,否则请求就会挂起。
Express 应用可使用如下几种中间件:
应用级中间件
路由级中间件
错误处理中间件
内置中间件
第三方中间件
使用可选则挂载路径,可在应用级别或路由级别装载中间件。另外,你还可以同时装在一系列中间件函数,从而在一个挂载点上创建一个子中间件栈。
应用级中间件
应用级中间件绑定到 app 对象 使用 app.use() 和 app.METHOD(), 其中, METHOD 是需要处理的 HTTP 请求的方法,例如 GET, PUT, POST 等等,全部小写。例如:1
var app = express();
// 没有挂载路径的中间件,应用的每个请求都会执行该中间件
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
// 挂载至 /user/:id 的中间件,任何指向 /user/:id 的请求都会执行它
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
// 路由和句柄函数(中间件系统),处理指向 /user/:id 的 GET 请求
app.get('/user/:id', function (req, res, next) {
res.send('USER');
});
下面这个例子展示了在一个挂载点装载一组中间件。
// 一个中间件栈,对任何指向 /user/:id 的 HTTP 请求打印出相关信息
app.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
作为中间件系统的路由句柄,使得为路径定义多个路由成为可能。在下面的例子中,为指向 /user/:id 的 GET 请求定义了两个路由。第二个路由虽然不会带来任何问题,但却永远不会被调用,因为第一个路由已经终止了请求-响应循环。1
// 一个中间件栈,处理指向 /user/:id 的 GET 请求
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id);
next();
}, function (req, res, next) {
res.send('User Info');
});
// 处理 /user/:id, 打印出用户 id
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id);
});
如果需要在中间件栈中跳过剩余中间件,调用 next('route') 方法将控制权交给下一个路由。 注意: next('route') 只对使用 app.VERB() 或 router.VERB() 加载的中间件有效。
// 一个中间件栈,处理指向 /user/:id 的 GET 请求
app.get('/user/:id', function (req, res, next) {
// 如果 user id 为 0, 跳到下一个路由
if (req.params.id == 0) next('route');
// 否则将控制权交给栈中下一个中间件
else next(); //
}, function (req, res, next) {
// 渲染常规页面
res.render('regular');
});
// 处理 /user/:id, 渲染一个特殊页面
app.get('/user/:id', function (req, res, next) {
res.render('special');
});
路由级中间件
路由级中间件和应用级中间件一样,只是它绑定的对象为 express.Router()。
var router = express.Router();
路由级使用 router.use() 或 router.VERB() 加载。
上述在应用级创建的中间件系统,可通过如下代码改写为路由级:1
var app = express();
var router = express.Router();
// 没有挂载路径的中间件,通过该路由的每个请求都会执行该中间件
router.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
// 一个中间件栈,显示任何指向 /user/:id 的 HTTP 请求的信息
router.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
// 一个中间件栈,处理指向 /user/:id 的 GET 请求
router.get('/user/:id', function (req, res, next) {
// 如果 user id 为 0, 跳到下一个路由
if (req.params.id == 0) next('route');
// 负责将控制权交给栈中下一个中间件
else next(); //
}, function (req, res, next) {
// 渲染常规页面
res.render('regular');
});
// 处理 /user/:id, 渲染一个特殊页面
router.get('/user/:id', function (req, res, next) {
console.log(req.params.id);
res.render('special');
});
// 将路由挂载至应用
app.use('/', router);
错误处理中间件
错误处理中间件有 4 个参数,定义错误处理中间件时必须使用这 4 个参数。即使不需要 next 对象,也必须在签名中声明它,否则中间件会被识别为一个常规中间件,不能处理错误。
错误处理中间件和其他中间件定义类似,只是要使用 4 个参数,而不是 3 个,其签名如下: (err, req, res, next)。1
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
请参考 错误处理 一章了解更多关于错误处理中间件的内容。
内置中间件
从 4.x 版本开始,, Express 已经不再依赖 Connect 了。除了 express.static, Express 以前内置的中间件现在已经全部单独作为模块安装使用了。请参考 中间件列表。
express.static(root, [options])
express.static 是 Express 唯一内置的中间件。它基于 serve-static,负责在 Express 应用中提托管静态资源。
参数 root 指提供静态资源的根目录。
可选的 options 参数拥有如下属性。
属性 描述 类型 缺省值
dotfiles 是否对外输出文件名以点(.)开头的文件。可选值为 “allow”、“deny” 和 “ignore” String “ignore”
etag 是否启用 etag 生成 Boolean true
extensions 设置文件扩展名备份选项 Array []
index 发送目录索引文件,设置为 false 禁用目录索引。 Mixed “index.html”
lastModified 设置 Last-Modified 头为文件在操作系统上的最后修改日期。可能值为 true 或 false。 Boolean true
maxAge 以毫秒或者其字符串格式设置 Cache-Control 头的 max-age 属性。 Number 0
redirect 当路径为目录时,重定向至 “/”。 Boolean true
setHeaders 设置 HTTP 头以提供文件的函数。 Function
下面的例子使用了 express.static 中间件,其中的 options 对象经过了精心的设计。1
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
}
}
app.use(express.static('public', options));
每个应用可有多个静态目录。
app.use(express.static('public'));
app.use(express.static('uploads'));
app.use(express.static('files'));
更多关于 serve-static 和其参数的信息,请参考 serve-static 文档。
第三方中间件
通过使用第三方中间件从而为 Express 应用增加更多功能。
安装所需功能的 node 模块,并在应用中加载,可以在应用级加载,也可以在路由级加载。
下面的例子安装并加载了一个解析 cookie 的中间件: cookie-parser
$ npm install cookie-parser1
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
// 加载用于解析 cookie 的中间件
app.use(cookieParser());
connect中间件例子:
Connect is an extensible HTTP server framework for node using “plugins” known as middleware.1
var connect = require('connect');
var http = require('http');
var app = connect();
// gzip/deflate outgoing responses
var compression = require('compression');
app.use(compression());
// store session state in browser cookie
var cookieSession = require('cookie-session');
app.use(cookieSession({
keys: ['secret1', 'secret2']
}));
// parse urlencoded request bodies into req.body
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
// respond to all requests
app.use(function(req, res){
res.end('Hello from Connect!\n');
});
//create node.js http server and listen on port
http.createServer(app).listen(3000);
Install Connect
$ npm install connect
Create an app
The main component is a Connect “app”. This will store all the middleware added and is, itself, a function.
var app = connect();
Use middleware
The core of Connect is “using” middleware. Middleware are added as a “stack” where incoming requests will execute each middleware one-by-one until a middleware does not call next() within it.1
app.use(function middleware1(req, res, next) {
// middleware 1
next();
});
app.use(function middleware2(req, res, next) {
// middleware 2
next();
});
Mount middleware
The .use() method also takes an optional path string that is matched against the beginning of the incoming request URL. This allows for basic routing.1
app.use('/foo', function fooMiddleware(req, res, next) {
// req.url starts with "/foo"
next();
});
app.use('/bar', function barMiddleware(req, res, next) {
// req.url starts with "/bar"
next();
});
Error middleware
There are special cases of “error-handling” middleware. There are middleware where the function takes exactly 4 arguments. Errors that occur in the middleware added before the error middleware will invoke this middleware when errors occur.1
app.use(function onerror(err, req, res, next) {
// an error occurred!
});
Create a server from the app
The last step is to actually use the Connect app in a server. The .listen() method is a convenience to start a HTTP server.
var server = app.listen(port);
The app itself is really just a function with three arguments, so it can also be handed to .createServer() in Node.js.
var server = http.createServer(app);
第三方中间件
这里列出的是部分 Express 中间件组件:
body-parser: previously express.bodyParser, json, and urlencoded. See also:
body
co-body
raw-body
compression - previously express.compress
connect-image-optimus: Connect/Express middleware for optimal image serving. Switches to webp/jpegxr if possible.
connect-timeout: previously express.timeout
cookie-parser: previously express.cookieParser
cookie-session: previously express.cookieSession
csurf: previousy express.csrf
errorhandler: previously express.errorHandler
express-debug: unobtrusive development tool that adds a tab with information about req, session, locals, and more to your application.
express-partial-response: Express middleware for filtering-out parts of JSON responses based on the fields query-string; using Google API’s Partial Response.
express-session: previously express.session
express-simple-cdn: easily use a CDN for your static assets, with multiple host support (ex. cdn1.host.com, cdn2.host.com).
express-slash: Express middleware for people who are strict about trailing slashes.
express-stormpath: Express middleware for user storage, authentication, authorization, SSO, and data security.
express-uncapitalize: redirect HTTP requests containing uppercase to a canonical lowercase form.
join-io: join files on a fly to reduce requests count
method-override: previously express.methodOverride
morgan: previously logger
passport: Express middleware for authentication.
response-time: previously express.responseTime
serve-favicon: previously express.favicon
serve-index: previousy express.directory
serve-static: for serving static content
static-expiry: fingerprinted URLs/Caching Headers for static assets including external domain(s) support.
vhost: previously express.vhost
view-helpers: An express middleware that provides common helper methods to the views.
express.cookieParser
cookies and keygrip
express.limit
raw-body
express.multipart
connect-busboy
multer
connect-multiparty
express.query
qs
express.staticCache
st
connect-static
Modules
Routers - routes HTTP traffic to different handlers
Request modules - modules that do stuff with req
Response modules - modules that do stuff with res
Route handlers - modules that are route handlers, like static servers
Templates - minimalist templating systems
Validators - modules that do HTTP body validation
Sessions - modules that associate sessions with a request
Modules - general modules for web servers.
Routers
routes
routes is the express.js router broken out into a standalone module. You can add route handlers and you can match an url on the router to get the right route handler
routes-router
routes-router uses routes but creates a function handler(req, res) {} function that you can plug into your http server. It handles error handling (optionally with domains) & 404’s for you by default. This is for convenience. It’s recommended you read the source code and write your own server request handler in your application.
mapleTree
An alternative router that is tree based and might be more efficient. It’s also more flexible in how it finds the correct route handler for any given url.
http-methods
http-methods is like a router but instead of routing on req.url it routes on the req.method. You can easily create a single route handler that dispatches to different functions based on method.
egress
A “pragmatic router,” egress is uniquely designed for tree-like routing tables. It can be used on its own or as Connect middleware.
Request modules
body
A set of asynchronous functions that parses the body of out of a req. It can also parse form encoded & json encoded bodies. body will limit the amount of body parsing to 1MB by default to prevent buffer overflows.
raw-body
raw-body will parse the body of a readable stream as a Buffer. It has a limiting mechanism to limit the size of the body to prevent buffer overflows.
cookies and keygrip
Read the cookies out of a req. Also has functionality to set cookies on the res. Use cookies with keygrip for signing cookies using rotated credentials.
Response modules
send-data
Send different types of resources to the client, like json or error or html. This module will set the headers properly on your behalf.
redirecter
Sends a proper HTTP redirect response to a res.
serve-favicon
Favicon serving middleware.
serve-file-download
Sets appropriate content-disposition header and pipes data to res.
Route handlers
st
st is a static file handler. It’s efficient and handles cache headers properly.
serve-browserify
serve-browserify is like a static file handler for javascript files but will browserify those files transparently on the fly. Optionally handles caching & gzipping.
npm-less
npm-less is like a static file handler for css files but will compile LESS files transparently on the fly. Optionally handles caching & gzipping.
filed
filed is a streaming file handler. This allows you to serve streaming files with the correct HTTP headers without caching the files in memory.
request
request allows you to make HTTP client requests to other servers. You can use request in your web server to forward a HTTP response from a 3rd party server to your res
Templates
hyperscript
hyperscript is an easy way to create templates in javascript. This allows you to use require for template inheritance and functions for template re-use. It’s the simplest templating system that works as it’s pure javascript.
consolidate.js
consolidate is a large wrapper around many popular templating languages that exposes the same API for each templating language.
Validators
validate-form
validate-form is a validation library that you can use to define a schema (a function) to validate arbitrary objects. validate-form is recursively made up of small functions so its really easy to add new validation logic.
joi
joi is another validation library. It allows you to define complex schemas using a chaining syntax.
is-my-json-valid
is-my-json-valid is a JSONSchema validator that uses code generation to be extremely fast.
Sessions
redsess
redsess is a redis backed session library. It creates an asynchronous session interface based upon a req/res pair. It will handle managing your session id & cookies for you.
level-session
level-session is a levelDB backed session library. It creates an asynchronous session interface based upon a req/res pair. It will handle managing your session id & cookies for you.
generic-session
generic-session is like redsess & level-session but has a MemoryStore interface for storing sessions in memory. This is great for tests.
pwd
pwd is a module for hashing a password. The first hash will generate a salt for it. You can then verify the password a second time with the salt to check hashes. This is great for a /login & /signup flow.
Modules
config-chain
config-chain makes it easy to load configuration from anywhere. This is a great way of setting up a cascading config system for your production web server.
static-config
static-config is a config loader for static application configuration. It has an accessible api to set up a rigid cascading config loader that can be modified to sanely integrate with tests.
error
error makes it easy to create re-usable errors that contain meta information about what went wrong.
bole
bole is a tiny flexible JSON logger that outputs ndjson.